//
//  AddWordVC.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/9/10.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "AddWordVC.h"
#import "IWTextView.h"
#import <objc/runtime.h>
#import <objc/message.h>
#import "IGPushiGalleryListVC.h"
#import "IGiGalleryEqu.h"
#import "IGiGalleryListApi.h"
#import "IGiGalleryPushApi.h"

@interface AddWordVC ()<UITextViewDelegate>
{
    UIImageView *imageV;
    UIImageView *subImageV;
    IWTextView*textL;
    CGFloat scale;
    CGFloat scale1;
    NSString *str;
}
@property (nonatomic, strong) NSArray *iGalleryListArr;
@property (nonatomic, strong) IGiGalleryListApi *igalleryListApi;;
@end

@implementation AddWordVC

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"加字推送";
    self.title = NSLocalizedString(@"Push with Comment", nil);
    self.view.backgroundColor = [UIColor mainBackgroundColor];
//    [self ig_setupRightButtonItemWithTitle:@"推送" image:nil highLightedImage:nil];
    str = NSLocalizedString(@"Please Input Words for Push", nil);
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Push", nil) image:nil highLightedImage:nil];
    [self creatImageV];
    [self requestIGlist];
}

- (void)creatImageV
{
    imageV = [[UIImageView alloc] init];
    imageV.contentMode = UIViewContentModeScaleAspectFit;
    imageV.userInteractionEnabled = YES;
    [self.view addSubview:imageV];
    CGFloat wid;
    UIImage *image;
    
    subImageV = [[UIImageView alloc] init];
    [subImageV sd_setImageWithURL:[NSURL URLWithString:_recommend.image]];
    subImageV.contentMode = UIViewContentModeScaleAspectFit;
    subImageV.clipsToBounds = YES;
    [imageV addSubview:subImageV];
    if ([_recommend.plates isEqualToString:@"1"] || ([_recommend.plates isEqualToString:@"3"] && [_recommend.imageWidth floatValue] >= [_recommend.imageHeight floatValue]))
    {
        //横图
        image = [UIImage imageNamed:@"home_gallery"];
        scale = image.size.width / image.size.height;
        wid = KSCREENWIDTH - 20;
        [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.right.mas_equalTo(-10);
            make.top.mas_equalTo(84);
            make.height.mas_equalTo(wid/scale);
        }];
        scale1 = 16 / 9;
        [subImageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(wid/10);
            make.right.mas_equalTo(-wid/10);
            make.centerY.mas_equalTo(imageV.centerY);
            make.height.mas_equalTo(wid/10*8/scale1);
        }];
    }
    else if ([_recommend.plates isEqualToString:@"2"] || ([_recommend.plates isEqualToString:@"3"] && [_recommend.imageHeight floatValue] >= [_recommend.imageWidth floatValue]))
    {
        //竖图
        image = [UIImage imageNamed:@"home_gallery1"];
        scale = image.size.width / image.size.height;
        wid = KSCREENWIDTH * 3 / 5;
        [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(KSCREENWIDTH/5);
            make.right.mas_equalTo(-KSCREENWIDTH/5);
            make.top.mas_equalTo(74);
            make.height.mas_equalTo(wid/scale);
        }];
        scale1 = 9 / 16;
        [subImageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(wid/scale/10);
            make.bottom.mas_equalTo(-wid/scale/10);
            make.centerX.mas_equalTo(imageV.centerX);
//            make.width.mas_equalTo(wid/scale/10*8*scale1);
        }];
    }
    imageV.image = image;
    
    textL = [[IWTextView alloc] initWithFrame:CGRectZero];
    textL.layer.masksToBounds = YES;
    textL.delegate = self;
    textL.backgroundColor = [UIColor blackColor];
    textL.alpha = 0.7;
    textL.font = [UIFont font14];
    textL.delegate = self;
    textL.textAlignment = NSTextAlignmentCenter;
    [textL addObserver:self forKeyPath:@"contentSize"options:NSKeyValueObservingOptionNew context:nil];
    textL.textColor = [UIColor c3Color];
    textL.returnKeyType = UIReturnKeySend;
    [imageV addSubview:textL];
    [textL becomeFirstResponder];
    [textL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(35);
        make.right.mas_equalTo(-35);
        make.top.mas_equalTo(35);
        make.height.mas_equalTo(20);
    }];
//    [self setTextLFrame:@"初始化"];
    [self setTextLFrame:NSLocalizedString(@"Initialization", nil)];
}

- (void)setTextLFrame:(NSString *)str
{
    CGFloat wid = textL.width;
    CGSize sizeStr = [Tool getLabelSizeWithText:str AndWidth:wid AndFont:[UIFont font14] attribute:nil];
    [textL mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(sizeStr.height + 12);
    }];
    textL.layer.cornerRadius = 10;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"])
    {
        CGFloat deadSpace = ([textL bounds].size.height - [textL contentSize].height);
        CGFloat inset = MAX(0, deadSpace/2.0);
        textL.contentInset = UIEdgeInsetsMake(inset, textL.contentInset.left, inset, textL.contentInset.right);
    }
}

//推送
- (void)ig_rightButtonPressed:(id)sender
{
    [self.view endEditing:YES];
    [textL resignFirstResponder];
    if (textL.text.length == 0 || [textL.text isEqualToString:str])
    {
//        [self presentMessageTips:str];
        [self presentMessageTips:NSLocalizedString(@"Please Input Words for Push", nil)];
        return;
    }
    if (self.iGalleryListArr.count == 0)
    {
//        [self presentMessageTips:@"当前无绑定设备"];
        [self presentMessageTips:NSLocalizedString(@"No linked device found", nil)];
    }
    else if (self.iGalleryListArr.count == 1)
    {
        [self pushToDev];
    }
    else
    {
        IGPushiGalleryListVC *listVC = [[IGPushiGalleryListVC alloc] initWithType:IGPushiGalleryType1NTpush];
        listVC.recommend = self.recommend;
        listVC.pushText = textL.text;
        [UIViewController ig_pushViewController:listVC animated:YES];
    }
}

-(void)requestIGlist
{
    self.igalleryListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    __weak typeof(self) weakSelf = self;
    [self.igalleryListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model = resp.data;
            weakSelf.iGalleryListArr = [NSArray arrayWithArray:model.equs];
        }
    }];
}

- (void)pushToDev
{
    IGiGalleryEqu *equ = self.iGalleryListArr[0];
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:@[equ.macId] pIds:@[self.recommend.aId]];
    pushApi.isTPush = @"1";//加字推送
    pushApi.text = textL.text;
//    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
//            [self presentMessageTips:@"推送成功..."];
            [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
        }
    }];
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView == textL)
    {
        if ([Tool convertToByte:textView.text] >= 15)
        {
//            [self showSuccessText:@"只能输入15个字"];
            [self showSuccessText:NSLocalizedString(@"No more than 15 characters.", nil)];
            [textView resignFirstResponder];
            return;
        }
        if (textView.text.length < 1)
        {
//            [self setTextLFrame:str];
            [self setTextLFrame:NSLocalizedString(@"No more than 15 characters.", nil)];
            return;
        }
        [self setTextLFrame:textView.text];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1)
    {
        textView.text = NSLocalizedString(@"Please Input Words for Push", nil);
    }
    [self setTextLFrame:textView.text];
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:NSLocalizedString(@"Please Input Words for Push", nil)])
    {
        textView.text=@"";
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [self ig_rightButtonPressed:nil];
        [self.view endEditing:YES];
        [textL resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    
    [textL resignFirstResponder];
}

- (void)dealloc
{
    [textL removeObserver:self forKeyPath:@"contentSize"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
